import React, { Component } from "react";
import { Form, Input, Button, Modal, Transfer, message, Tag } from "antd";
import axios from "axios";
import qs from "qs";
import OrgTree from "./OrgTree";
import "../mock/user003001";
import "../mock/user003002";

export default class EditJoin extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      addVisible: false,
      //   mockData: ["李亮", "张明", "李飞", "王培"], //职工列表
      hostMockData: [], //职工列表
      joinMockData: [], //职工列表
      hostTargetKeys: [props.record.meetingHost],
      joinTargetKeys: props.record.meetingJoin,
      //   hostSelectedKeys: [props.record.meetingHost],
      //   joinSelectedKeys: [props.record.meetingJoin],
      rules: [
        {
          required: false,
          message: "此项不可为空",
        },
      ],
      treeData: [],
      getDataSource: props.getDataSource,
    };
    this.formRef = React.createRef();
    this.setTreeData = this.setTreeData.bind(this);
    this.treeOnSelect = this.treeOnSelect.bind(this);
  }

  /**添加主持人 */
  handleHostChange = (hostTargetKeys) => {
    this.setState({ hostTargetKeys });
  };
  /**添加参会人 */
  handleJoinChange = (joinTargetKeys) => {
    this.setState({ joinTargetKeys });
  };
  /**机构数据 */
  setTreeData = (treeData) => {
    setTimeout(() => {
      this.setState({ treeData });
    }, 0);
  };

  /*点击部门列表,展示部门人员 */
  treeOnSelect = (isHost, value) => {
    console.log(value);
    // this.getMock(isHost, value);
    axios
      .get("searchUsers.rst?orgId=" + value[0])
      .then((res) => {
        let response = res.data;
        // response = response.data;
        console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          if (isHost) {
            this.setState({
              hostMockData: res.map((person) => {
                return {
                  key: person.EMPID + "_" + person.EMPNAME,
                  title: person.EMPID + "_" + person.EMPNAME,
                };
              }),
            });
          } else {
            this.setState({
              joinMockData: res.map((person) => {
                return {
                  key: person.EMPID + "_" + person.EMPNAME,
                  title: person.EMPID + "_" + person.EMPNAME,
                };
              }),
            });
          }
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  /**弹出对话框 */
  showAddModal = () => {
    const record = this.props.record;
    console.log(record);
    /**弹出 */
    this.setState({
      addVisible: true,
    });
    /**等待form渲染 */
    setTimeout(() => {
      this.formRef.current.setFieldsValue({
        address: record.meetingAddress,
        content: record.meetingContent,
        meetingRoom: record.meetingRoom,
      });
    }, 100);
  };

  onFinish = (values) => {
    /**表单字段在不做改动时返回时会为undefined，需要手动判断 */

    let pass = true;
    let messCon = "";
    /**表单返回值 currVal*/
    const currVal = this.formRef.current.getFieldsValue();
    console.log(currVal);
    // console.log(currVal)
    /**判断日期，地点，内容 */

    /**判断主持人和参会人 */

    if (this.state.joinTargetKeys.length === 0) {
      pass = false;
      messCon = "参会人";
    }

    /** */
    if (pass) {
      this.setState({ loading: true });

      /**修改会议数据 */
      axios({
        url: "updatemeeting.rst",
        method: "post",
        data: qs.stringify({
          id: this.props.record.key,
          participator: this.state.joinTargetKeys.join(),
          host: this.props.record.meetingHost,
          enable: this.props.record.enable,
        }),
      })
        .then((res) => {
          let response = res.data;
          if (response.resultCode === 0) {
            /**清空并关闭添加表单 */
            message.success("提交成功");
            this.setState({ loading: false, addVisible: false });
            /**重新渲染会议列表 */
            this.props.getDataSource();
          } else {
            message.error("提交失败");
          }
        })
        .catch((error) => {
          message.error("提交失败");
        });
    } else {
      /**有字段为空 */
      message.error(messCon + "字段不可为空！");
    }
  };

  handleCancel = () => {
    const { meetingJoin } = this.props.record;
    /**清空修改表单状态 */
    // this.formRef.current.resetFields();
    this.setState({
      joinTargetKeys: meetingJoin,
    });
    this.setState({ loading: false, addVisible: false });
  };

  componentDidMount() {
    // this.getMock();
  }
  /**关闭Tag */

  handleJoinTagClose = (removedTag) => {
    const joinTargetKeys = this.state.joinTargetKeys.filter(
      (joinTargetKeys) => joinTargetKeys !== removedTag
    );
    console.log(joinTargetKeys);
    this.setState({ joinTargetKeys });
  };
  /*遍历插入Tag */
  joinForMap = (tag) => {
    // console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="blue"
          onClose={(e) => {
            e.preventDefault();
            this.handleJoinTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };

  render() {
    const { addVisible, loading } = this.state;
    /**添加会议数据 */

    const { rules, joinMockData, joinTargetKeys, treeData } = this.state;
    const joinTag = joinTargetKeys.map(this.joinForMap);
    return (
      <>
        {/* <Button type="primary" onClick={this.showAddModal}>
          修改
        </Button> */}
        <span className="editJoin" onClick={this.showAddModal}>
          {joinTargetKeys}
        </span>
        <Modal
          visible={addVisible}
          title="编辑参加人"
          centered
          onCancel={this.handleCancel}
          //   onOk={this.handleAdd}
          width={1000}
          //   onCancel={this.handleCancel}
          footer={null}
          destroyOnClose={true}
        >
          <Form
            name="add-meeting"
            onFinish={this.onFinish}
            className="search-meet"
            ref={this.formRef}
          >
            <Form.Item name="join" label="参加人" rules={rules}>
              {joinTag}
              <OrgTree
                treeData={treeData}
                setTreeData={this.setTreeData}
                treeOnSelect={this.treeOnSelect}
                isHost={false}
              />
              <Transfer
                dataSource={joinMockData}
                targetKeys={joinTargetKeys}
                // selectedKeys={joinTargetKeys}
                showSearch
                listStyle={{
                  width: 250,
                  height: 200,
                }}
                operations={["添加", "移出"]}
                onChange={this.handleJoinChange}
                render={(item) => item.title}
              />
            </Form.Item>

            <Button type="primary" htmlType="submit" loading={loading}>
              确定
            </Button>
          </Form>
        </Modal>
      </>
    );
  }
}
